// todo...
import { t } from "../../locale";
import { mainAppRouter } from "../../router";
import store from "../../store";
import defaultSetting from "./defaultSetting";
// import { loadQKApp } from "../../micro_apps/index";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { createVNode, toRaw } from "vue";
// import microState from "../../micro_apps/session";
import BLCOMMON from "bl-common-vue3";
import request from "./request";
import moment from "moment";
import shareds from "@/common/utils/shared";
import _ from "lodash";

const utils = {
  imgAction: request.BASE_URL + "/public/system/uploadImage",
  fileAction: request.BASE_URL + "/public/system/uploadFile",
  localFileAction: request.BASE_URL + "/village/room/import/file",
  staticPath:
    (window.__MICRO_APP_ENVIRONMENT__
      ? window?.microApp?.getData()?.props?.mainRequestDomain
      : defaultSetting.requestDomain || "http://127.0.0.1") +
    "/public_web/static/",
  staticUeditorEditorPaths:
    (window.__MICRO_APP_ENVIRONMENT__
      ? window?.microApp?.getData()?.props?.mainRequestDomain
      : defaultSetting.requestDomain || "http://127.0.0.1") +
    "/public_web/UEditor/",
  staticPathes: window.__MICRO_APP_ENVIRONMENT__
    ? window?.microApp?.getData()?.props?.mainRequestDomain
    : defaultSetting.requestDomain || "http://127.0.0.1",
  // 数字验证正则
  numberReg: /^\d+(\.\d+)?$/,
  // 手机号正则
  phoneReg: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
  urlReg: /(http|https):\/\/([\w.]+\/?)\S*/,
  // 座机电话正则
  telReg: /^(0[0-9]{2,3}\-)([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/,

  /**
   * @description:  主应用页面跳转
   * @param {String} link 必传 linkList对应的key值 或者 直接为跳转链接（此时linkList不传或为false)
   * @param {String} type 可选 跳转类型replace push
   * @param {Object} linkList 可选 自定义的映射路由表(对象)
   */
  goUrl: (link = "", type = "push", linkList = false) => {
    if (!link) {
      return;
    }
    if (linkList) {
      link = linkList[link];
    }
    // utils.consoleInfo(type, "type");
    if (type == "push") {
      mainAppRouter.push(link);
    } else if (type == "replace") {
      mainAppRouter.replace(link);
    }
  },
  goMainRoute: ({ name = "", type = "push", query = {} }) => {
    mainAppRouter[type]({
      name,
      query,
    });
  },

  /**
   * @description: 设置cookie
   * @param {String}name cookie名称
   * @param {*}value cookie值
   * @param {Number}exdays cookie保存天数
   */
  setCookie: (name, value, exdays = 720) => {
    return new Promise((resolve) => {
      let d = new Date();
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
      let expires = "expires=" + d.toUTCString();
      document.cookie = name + "=" + value + "; " + "path=/;" + expires;
      resolve();
    });
  },

  /**
   * @description: 移除存储
   * @param {String}name 存储变量名
   * @param {Boolean} isCache 是否持久存储
   */
  removeStorage: (name, isCache) => {
    const storageName = utils.getStorageName(name);
    if (isCache) {
      sessionStorage.removeItem(storageName);
    } else {
      localStorage.removeItem(storageName);
    }
  },

  // 子菜单需要渲染的路由
  goAppRoute: (appName, pathName, query = {}) => {
    // loadQKApp({
    //   appName,
    //   pathName,
    //   params: query,
    // });
  },

  // 为了处理子应用跳转子应用
  handleAppRouteChange: (route) => {
    const userMenu = store.getters.userMenu;
    let result = getMenuByUserMenu(userMenu, route.name);
    if (
      result &&
      result.alias != route.name &&
      result.children &&
      result.children.length
    ) {
      store.dispatch("SetCurrentTopMenu", result);
      result = getMenuByUserMenu(result.children, route.name);
      // microState
      //   .setMicroState({
      //     [`${route.app}SideMenu`]: result,
      //   })
      //   .then(() => {
      //     // loadQKApp({
      //     //   appName: route.app,
      //     //   pathName: route.name,
      //     //   params: route.query,
      //     // });
      //   });
    } else {
      if (result) {
        store.dispatch("SetCurrentTopMenu", result);
      }
      // loadQKApp({
      //   appName: route.app,
      //   pathName: route.name,
      //   params: route.query,
      // });
    }
  },

  /**
   * @description: 确认弹框（删除确认） 重写是为了多语言
   * @param {*} 同ant design api
   */
  modalConfirm: ({
    title = "提示",
    content = {},
    centered = false,
    onOk,
    onCancel,
    okType = "primary",
  }) => {
    Modal.confirm({
      title: () => title,
      content: () => content,
      okText: () => "确定",
      icon: () => createVNode(ExclamationCircleOutlined),
      okType,
      cancelText: () => "取消",
      centered,
      onOk() {
        onOk && onOk();
      },
      onCancel() {
        onCancel && onCancel();
      },
    });
  },

  /**
   * @description: 复制内容到剪切板
   * @param {String} content
   */
  copyText: (content) => {
    let ele = document.createElement("input"); //创建一个input标签
    ele.setAttribute("value", content); // 设置改input的value值
    document.body.appendChild(ele); // 将input添加到body
    ele.select(); // 获取input的文本内容
    document.execCommand("copy"); // 执行copy指令
    document.body.removeChild(ele); // 删除input标签
    message.success("复制成功！");
  },

  /**
   * @description: 设置页面标题
   * @param {String} title
   */
  setDocumentTitle: () => {
    const systemName = store.getters.basicConfig.system_name;
    document.title = `${systemName}`;
    const ua = navigator.userAgent;
    const regex = /\bMicroMessenger\/([\d\.]+)/;
    if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
      const i = document.createElement("iframe");
      i.src = "/favicon.ico";
      i.style.display = "none";
      i.onload = function () {
        setTimeout(function () {
          i.remove();
        }, 9);
      };
      document.body.appendChild(i);
    }
  },
  // 是否是开发环境
  isEnv: () => {
    if (process.env.NODE_ENV === "production") {
      return false;
    }
    return true;
  },
  /**
   * @description: 动态获取keep-alive数组
   * @param {Array} list 路由表
   * @param {Array} result
   */
  getKeepAliveRoutes: (list, result) => {
    for (let item of list) {
      if (item.meta && item.meta.keepAlive === true) {
        result.push(item.name);
      }
      if (item.children && item.children.length) {
        utils.getKeepAliveRoutes(item.children, result);
      }
    }
  },

  /**
   * @description: 为公共组件提供的请求方法
   */
  commonRequest: (emitObj) => {
    const { params, success, fail } = emitObj;
    const { method, server, url, extra = {} } = params;
    request[method](server, url, extra)
      .then((res) => success(res))
      .catch((err) => fail(err));
  },

  /**
   * @description: 子应用向子应用发送的公共数据
   */
  getAppToChildData: ({ loadInfo = {}, propsInfo = {} }) => {
    return {
      ...loadInfo,
      props: {
        // 主应用数据
        ...store.getters.mainAppInfo,
        ...propsInfo,
      },
    };
  },

  /**
   * @description: 楼宇信息转换为treeData
   * @param {Array}data 接口返回
   * @return {Array}list treeData
   */
  transformVilliageData: (data) => {
    let list = [];
    if (data.length) {
      list = data.map((item) => {
        let vItem = {};
        vItem.key = `parent_${item.id}`;
        vItem.value = `parent_${item.id}`;
        vItem.title = item.name;
        vItem.children = item.buildList.map((item2) => {
          let bItem = {};
          bItem.key = item2.id;
          bItem.value = item2.id;
          bItem.title = item2.build_name;
          return bItem;
        });
        return vItem;
      });
    }
    return list;
  },

  /**
   * @description: 楼宇选中与提交字段互转
   * @param {Array | Object}
   * @return {Array | Object}
   */
  transformBuildData: (data) => {
    if (data.ids) {
      // {ids,names} => {label,value}
      return data.ids.map((id) => {
        return {
          value: id,
          label: data.names[id],
        };
      });
    } else {
      // {label,value} => {ids,names}
      let ids = [];
      let names = {};
      if (data.length) {
        data.forEach((item) => {
          ids.push(item.value);
          names[item.value] = item.label || "";
        });
      }
      return { ids, names };
    }
  },

  /**
   * @description: 根据id获取部门内容
   * @param {String | Number} id 部门id
   * @param {Array} list 部门列表
   * @return {Object} 当前部门
   */
  getDepartmentById: (id, list) => {
    if (!id || !list || !list.length) {
      return;
    }
    for (let item of list) {
      if (item.key == id) {
        return item;
      }
      if (item.children && item.children.length) {
        const current = utils.getDepartmentById(id, item.children);
        if (current) {
          return current;
        }
      }
    }
  },

  /**
   * @description: 根据部门名称获取部门内容
   * @param {String | Number} id 部门id
   * @param {Array} list 部门列表
   * @param {Array} result 符合条件的列表
   */
  getDepartmentByName: (name, list, result) => {
    if (!name || !list || !list.length) {
      return;
    }
    for (let item of list) {
      if (item.title.indexOf(name) > -1) {
        result.push(item);
      }
      if (item.children && item.children.length) {
        utils.getDepartmentByName(name, item.children, result);
      }
    }
  },

  /**
   * @description: 获取省市区县等信息
   * @param {Number} level 当前等级
   * @param {Array} optionList 返回的列表
   * @param {Object} extra 其他信息： id 请求id ; leafLevel: 叶子节点等级
   */
  getAreaOptions: (level, extra = { id: "", leafLevel: 5 }, isShort = true) => {
    return new Promise((resolve) => {
      let requestUrl = "";
      let requestParams = {};
      switch (level) {
        case 1:
          // 省
          requestUrl = "/district/province_list";
          break;
        case 2:
          // 市
          requestUrl = "/district/city_list";
          requestParams = { province_id: extra.id };
          break;
        case 3:
          // 区
          requestUrl = "/district/district_list";
          requestParams = { city_id: extra.id };
          break;
        case 4:
          // 街道/乡
          requestUrl = "/district/street_list";
          requestParams = { district_id: extra.id };
          break;
        case 5:
          // 社区/村
          requestUrl = "/district/community_list";
          requestParams = { street_id: extra.id };
          break;
        default:
          requestUrl = "";
          break;
      }
      if (requestUrl) {
        let leafLevel = extra.leafLevel || 5;
        request.get("/public", requestUrl, requestParams).then((res) => {
          if (res.list) {
            let optionList = res.list.map((item) => ({
              value: item.area_code,
              label: isShort ? item.short_name : item.name,
              level,
              isLeaf: level == leafLevel,
            }));
            resolve(optionList);
          }
        });
      }
    });
  },

  /**
   * @description: 获取省市区信息  添加账号信息组件专用 选中之后会获取到名称(并非省市县号)
   * @param {Number} level 当前等级
   * @param {Array} optionList 返回的列表
   * @param {Object} extra 其他信息： id 请求id ; leafLevel: 叶子节点等级
   */
  getDistrictsOptions: (level, extra = { id: "", leafLevel: 2 }) => {
    return new Promise((resolve) => {
      let requestUrl = "";
      let requestParams = {};
      switch (level) {
        case 1:
          // 省
          requestUrl = "/org/province";
          break;
        case 2:
          // 市
          requestUrl = "/org/city";
          requestParams = { province: extra.id };
          break;
        default:
          requestUrl = "";
          break;
      }
      if (requestUrl) {
        let leafLevel = extra.leafLevel || 2;
        request.get("/pay", requestUrl, requestParams).then((res) => {
          if (res.list) {
            let optionList = [];
            if (level == 1) {
              optionList = res.list.map((item) => ({
                value: item.province_name,
                label: item.province_name,
                level,
                isLeaf: level == leafLevel,
              }));
            } else {
              optionList = res.list.map((item) => ({
                value: item.area_name,
                label: item.area_name,
                level,
                isLeaf: level == leafLevel,
              }));
            }

            resolve(optionList);
          }
        });
      }
    });
  },

  /**
   * @description: 整数前面补0
   * @param {Number} num 待处理的整数
   * @param {Number} len 需要的长度
   */
  prefixInteger: (num, len) => {
    return (Array(len).join("0") + num).slice(-len);
  },

  /**
   * @description: 表单验证为数字
   * @param {Object} rules 规则
   * @param {*} value 值
   */
  numberValidator: async (rules, value) => {
    // console.log("rules,value", rules, value);
    const valueNotEmpty = value || value == "0" ? true : false;
    if (rules.required && !valueNotEmpty) {
      return Promise.reject("必填项");
    }
    if (valueNotEmpty && !utils.numberReg.test(value)) {
      return Promise.reject("请输入数字");
    }
    return Promise.resolve();
  },
  // 自然数
  nNumberValidator: async (rules, value) => {
    const valueNegative = Number(value) < 0;
    if (rules.required && !value && value != 0) {
      return Promise.reject("必填项");
    }
    if (!utils.numberReg.test(value) || valueNegative) {
      return Promise.reject("请输入大于等于0的数字");
    }
    return Promise.resolve();
  },
  // 正数
  pNumberValidator: async (rules, value) => {
    // console.log("rules,value", rules, value);
    const valueNotEmpty = value ? true : false;
    if (rules.required && !valueNotEmpty) {
      return Promise.reject("必填，请输入大于0的数字");
    }
    if (valueNotEmpty && !utils.numberReg.test(value)) {
      return Promise.reject("请输入大于0数字");
    }
    return Promise.resolve();
  },

  /**
   * @description: 数组处理成树 （递归）
   */
  transListToTreeData: (list, rootValue) => {
    var arr = [];
    list.forEach((item) => {
      if (item.parent_id == rootValue) {
        const children = utils.transListToTreeData(list, item.id);
        if (children.length) {
          item.children = children;
        } else {
          item.children = [];
          item.isLeaf = true;
        }
        arr.push(item);
      }
    });
    return arr;
  },

  /**
   * @description: 将租金明细分组
   * @param {Object}
   * @return {Object}
   */
  getClauseDetailByGroup: (data, attribute = "lease") => {
    // 租金
    let leaseData = {};
    let leaseList = [];
    if (data.leaseData.length) {
      data.leaseData.forEach((item, index) => {
        item.reportStage = index + 1;
        if (!leaseData[item.group]) {
          leaseData[item.group] = [];
        }
        item.hasReceivePrice = !!item.receivePrice;
        leaseData[item.group].push(item);
      });
      for (let key in leaseData) {
        leaseList.push({
          key: "lease_" + key,
          belong: "lease",
          title: attribute == "property" ? "物业费" : "租金",
          group: key,
          list: leaseData[key],
        });
      }
    }
    // 分成
    let divideData = {};
    let divideList = [];
    if (data.divideData.length) {
      data.divideData.forEach((item, index) => {
        item.reportStage = index + 1;
        if (!divideData[item.group]) {
          divideData[item.group] = [];
        }
        item.hasReceivePrice = !!item.receivePrice;
        divideData[item.group].push(item);
      });
      for (let key in divideData) {
        divideList.push({
          key: "divide_" + key,
          belong: "divide",
          title: "分成",
          group: key,
          list: divideData[key],
        });
      }
    }
    let list = [...leaseList, ...divideList];
    list.sort((a, b) => {
      return a.group - b.group;
    });
    return {
      list: [
        {
          key: "bond",
          belong: "bond",
          title: "保证金",
          list: data.bondData,
        },
        ...list,
      ],
      receiveTotal: data.receiveTotal,
      bondTotal: data.bondTotal,
      receiveDiscount: data.receiveDiscount,
      taxAmountTotal: data.taxAmountTotal,
      leaseCount: leaseList.length,
      divideCount: divideList.length,
    };
  },

  // 获取分成比例值
  getDivideRatio: (clauseTerms, current) => {
    for (let i in clauseTerms) {
      let item = clauseTerms[i];
      console.log("-----------getDivideRatio", item);
      const { divide_mode, section_mode_unit } = item;
      if (
        divide_mode &&
        current.group == i &&
        moment(current.startDate).isBetween(
          item.charge_begintime,
          item.charge_endtime,
          null,
          "[]"
        )
      ) {
        // divide_mode_unit unit1固定比例 unit2全额阶梯分成 unit3超额阶梯分成
        if (divide_mode.length == 1) {
          return { mode: item.divide_mode_unit, ratio: divide_mode[0].ratio };
        } else {
          const value = Number(current.turnover);
          for (let divide of divide_mode) {
            if (
              section_mode_unit == "unit1" &&
              value > divide.minPrice &&
              (divide.maxPrice == -1 || value <= divide.maxPrice)
            ) {
              // 左开右闭
              return {
                mode: item.divide_mode_unit,
                ratio: divide.ratio,
                divideList: divide_mode,
              };
            }
            if (
              section_mode_unit == "unit2" &&
              value >= divide.minPrice &&
              (divide.maxPrice == -1 || value < divide.maxPrice)
            ) {
              // 左闭右开
              return {
                mode: item.divide_mode_unit,
                ratio: divide.ratio,
                divideList: divide_mode,
              };
            }
          }
        }
      }
    }
  },

  getRatioPrice: (currentItem, ratioInfo, rate = 0) => {
    let receivePrice = 0;
    let taxAmount = 0;
    console.log("-------------getRatioPrice", currentItem, ratioInfo);
    if (ratioInfo.mode == "unit3") {
      const { divideList } = ratioInfo;
      const index = divideList.findIndex(
        (item) => item.ratio == ratioInfo.ratio
      );
      for (let i = index; i >= 0; i--) {
        if (i == index) {
          receivePrice =
            (Number(currentItem.turnover) - Number(divideList[i].minPrice)) *
            divideList[i].ratio *
            0.01;
        } else {
          receivePrice =
            Number(receivePrice) +
            (Number(divideList[i].maxPrice) - Number(divideList[i].minPrice)) *
              divideList[i].ratio *
              0.01;
        }
      }
      taxAmount = (Number(receivePrice) * rate * 0.01).toFixed(2);
      receivePrice = (Number(receivePrice) * (1 + rate * 0.01)).toFixed(2);
      return { receivePrice, taxAmount };
    } else {
      receivePrice = Number(currentItem.turnover) * ratioInfo.ratio * 0.01;
    }
    taxAmount = (Number(receivePrice) * rate * 0.01).toFixed(2);
    receivePrice = (Number(receivePrice) * (1 + rate * 0.01)).toFixed(2);
    return { receivePrice, taxAmount };
  },

  setReceviePrice: (e) => {
    const {
      leaseList,
      currentItem,
      canZero = true,
      subIndex = -1,
      unitPoint = 2,
    } = e;
    return new Promise((resolve, reject) => {
      // takeHigh  非分成取高条款=0  分成取高条款+未取高=1 分成取高条款+取高=2
      if (currentItem.takeHigh != 0) {
        // 当前分成应收
        // 同期租金应收
        const leaseListItem = leaseList.find(
          (item) => item.belong == "lease" && item.group == currentItem.group
        );
        const leaseItem = leaseListItem.list.find(
          (item) => item.reportStage == currentItem.reportStage
        );
        let canSetCurrent = true;
        if (subIndex > -1) {
          // 如果有子分成
          const subItem = currentItem.mdate[subIndex];
          const subLeaseItem = leaseItem.mdate[subIndex];
          if (!canZero && !subItem.turnover) {
            subItem.receivePrice = 0;
            subItem.taxAmount = 0;
            subLeaseItem.takeHigh = subItem.takeHigh = 1;
          } else {
            subLeaseItem.takeHigh = subItem.takeHigh = 2;
          }
          // 计算父级总抽成、应收
          currentItem.receivePrice = 0;
          currentItem.taxAmount = 0;
          currentItem.turnover = 0;
          currentItem.mdate.forEach((item) => {
            currentItem.turnover += Number(item.turnover);
            currentItem.receivePrice += Number(item.receivePrice);
            currentItem.taxAmount += Number(item.taxAmount);
          });
          currentItem.receivePrice = Number(currentItem.receivePrice).toFixed(
            unitPoint
          );
          currentItem.taxAmount = Number(currentItem.taxAmount).toFixed(
            unitPoint
          );
          currentItem.turnover = Number(currentItem.turnover).toFixed(
            unitPoint
          );
          //  判断是否所有子分成都填写了
          canSetCurrent = subDiviceFinish(currentItem);
        }
        // 对比计算出应收
        const receivePrice = Number(currentItem.receivePrice);
        const leaseRecevicePrice = Number(leaseItem.receivePrice);
        delete currentItem.is_create;
        delete leaseItem.is_create;
        if (canSetCurrent) {
          // 如果子分成都写了或没有子分成，则可以判断当前分成是否取高了
          if (!canZero && !currentItem.turnover) {
            currentItem.receivePrice = 0;
            leaseItem.takeHigh = currentItem.takeHigh = 1;
          } else {
            leaseItem.takeHigh = currentItem.takeHigh = 2;
            if (leaseRecevicePrice >= receivePrice) {
              // 租金生效
              currentItem.is_create = false;
            } else {
              // 分成生效
              leaseItem.is_create = false;
            }
          }
        } else {
          leaseItem.takeHigh = currentItem.takeHigh = 1;
        }
        resolve({ currentItem, leaseItem });
      } else {
        if (subIndex > -1) {
          const subItem = currentItem.mdate[subIndex];
          if (!canZero && !subItem.turnover) {
            subItem.receivePrice = 0;
            subItem.taxAmount = 0;
          }
          currentItem.receivePrice = 0;
          currentItem.taxAmount = 0;
          currentItem.turnover = 0;
          let is_create = true;
          for (let item of currentItem.mdate) {
            currentItem.turnover += Number(item.turnover);
            if (item.receivePrice) {
              currentItem.receivePrice += Number(item.receivePrice);
            } else if (is_create) {
              is_create = false;
            }
            if (item.taxAmount) {
              currentItem.taxAmount += Number(item.taxAmount);
            }
          }
          currentItem.is_create = is_create;
          currentItem.receivePrice = Number(currentItem.receivePrice).toFixed(
            unitPoint
          );
          currentItem.taxAmount = Number(currentItem.taxAmount).toFixed(
            unitPoint
          );
          currentItem.turnover = Number(currentItem.turnover).toFixed(
            unitPoint
          );
        }
        resolve({ currentItem });
      }
    });
  },

  /**
   * @description: 获取随机数
   * @param {Number} num 位数
   * @return {String} result 值
   */
  getRandomUid: (num = 1) => {
    const number = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let result = "";
    for (let i = num; i--; ) {
      const index = parseInt(Math.random() * number.length);
      result += number[index];
    }
    return result;
  },

  /**
   * @description: 获取图片真实宽高
   * @param {String} url 图片地址
   * @param {Object} size 宽高
   */
  getImageSize: (url) => {
    return new Promise((resolve) => {
      const image = new Image();
      image.src = url;
      image.onload = function () {
        // console.log("图片原始高度", image.height);
        // console.log("图片原始宽度", image.width);
        resolve(image);
      };
    });
  },

  /**
   * @description: 表单验证为手机号
   */
  phoneValidator: async (rule, value) => {
    if (!value) {
      if (rule.required) {
        return Promise.reject("必填项");
      }
      return Promise.resolve();
    }
    if (!utils.phoneReg.test(value)) {
      return Promise.reject("请输入正确的手机号码");
    }
    return Promise.resolve();
  },

  /**
   * @description: 表单验证为手机号&&座机电话
   */
  phoneAndTelValidator: async (rule, value) => {
    if (!value) {
      if (rule.required) {
        return Promise.reject("必填项");
      }
      return Promise.resolve();
    }
    if (!utils.phoneReg.test(value) && !utils.telReg.test(value)) {
      return Promise.reject("请输入正确的手机或座机号码");
    }
    return Promise.resolve();
  },

  // 格式化小数
  parseNumber: (value, fixed = 2) => {
    const arr = String(value).split(".");
    if (!arr[1] || Number(arr[1]) == 0) {
      return value;
    }
    return Number(value).toFixed(fixed);
  },
  // 0
  isZero: (value) => {
    return parseFloat(value) == 0;
  },
  // 保留两位小数
  toFixed2: (value) => {
    return Number(value).toFixed(2);
  },
  // 排班判断是否为次日 list=[{start,end}]
  getShiftTimeDetail: (list) => {
    for (let index in list) {
      let listItem = list[index];
      if (index == 0) {
        listItem.startNextDay = false;
      } else {
        listItem.startNextDay =
          list[index - 1].endNextDay ||
          utils.compareTime(list[index - 1].end, listItem.start);
      }
      listItem.endNextDay =
        listItem.startNextDay ||
        utils.compareTime(listItem.start, listItem.end);
    }
    return list;
  },
  // 比较时间（时:分）大小 time1 > time2为true
  compareTime: (time1, time2) => {
    const timeArr1 = time1.split(":");
    const timeArr2 = time2.split(":");
    return (
      Number(timeArr1[0]) > Number(timeArr2[0]) ||
      (Number(timeArr1[0]) == Number(timeArr2[0]) &&
        Number(timeArr1[1]) > Number(timeArr2[1]))
    );
  },

  // 根据buildingList获取projectBuild
  getProjectBuildByBuildList: (list) => {
    let result = {
      buildId: [],
      villageId: [],
      projectBuild: [],
    };
    for (let item of list) {
      result.buildId.push(item.id);
      let villageId = item.village_id || item.extra.village_id;
      if (result.villageId.includes(villageId)) {
        const current = result.projectBuild.find((it) => it.id == villageId);
        current.build.push(item.id);
      } else {
        result.villageId.push(villageId);
        result.projectBuild.push({ id: villageId, build: [item.id] });
      }
    }
    return result;
  },

  // 根据build_bind获取当前房间的楼宇信息
  getBuildNameByBuildBind: (room, build_bind) => {
    if (room.build_name) {
      return room.build_name;
    }
    if (room.extra && room.extra.build_name) {
      return room.extra.build_name;
    }
    const { build } = build_bind;
    if (Array.isArray(build)) {
      const curBuild = build.find((it) => it.id == room.build_id);
      return curBuild ? curBuild.build_name : "--";
    }
    return build.build_name || "--";
  },

  // 根据build_bind获取当前房间的项目名称
  getVillageNameByBuildBind: (room, build_bind) => {
    if (room.village_name) {
      return room.village_name;
    }
    if (room.extra && room.extra.village_name) {
      return room.extra.village_name;
    }
    const { village } = build_bind;
    return village?.name || "--";
  },

  /**
   * @description: 检查项目楼宇信息并自动创建测试楼宇
   * 普通机构，弹出modal阻止，点击确认后自动创建
   * 特殊机构，直接自动创建
   */
  checkBuildsAndAutoCreate: () => {
    const { checkedBuildings } = store.getters.buildingInfo;
    const isSpecialOrg =
      store.getters.orgInfo && store.getters.orgInfo.org_special;
    console.log("checkBuildsAndAutoCreate", checkedBuildings, isSpecialOrg);
    if (!checkedBuildings || !checkedBuildings.length) {
      // 特殊机构自动创建
      if (isSpecialOrg) {
        request
          .post("/village", "/project/manage", {
            create_demo_data: 1,
          })
          .then((res) => {
            location.reload();
          });
      } else {
        Modal.confirm({
          title: "提示",
          content: "您需要先添加项目和楼宇才能正常使用哦~",
          icon: () => createVNode(ExclamationCircleOutlined),
          okText: "创建测试项目",
          centered: true,
          onOk: () => {
            request
              .post("/village", "/project/manage", {
                create_demo_data: 1,
              })
              .then((res) => {
                location.reload();
              });
          },
          cancelText: "手动添加",
          onCancel: () => {
            utils.goMainRoute({
              name: "villageList",
            });
          },
        });
      }
    }
  },

  /**
   * @description: 转换机构部门角色等数据
   * @param {Array}list
   * @return {Array}
   */
  getApartmentUserList: (list) => {
    return list.map((item) => {
      item.key = item.id;
      item.value = item.id;
      item.title = item.name;
      if (item.subcat && item.subcat.length) {
        item.children = utils.getApartmentUserList(item.subcat);
      } else {
        item.isLeaf = true;
      }
      delete item.subcat;
      return item;
    });
  },

  /**
   数值相加或减少计算精度的问题
   */
  countSum: (arr) => {
    if (!arr.length) return 0;
    arr = arr.map((v) => {
      if (v && !Number.isNaN(Number(v))) return Math.round(v * 100);
      return 0;
    });
    const result = arr.reduce((prev, curr) => {
      return prev + curr;
    }, 0);
    return result / 100;
  },

  hasParentWithClass: (element, className) => {
    let parent = element?.parentNode;
    while (parent) {
      if (parent?.classList?.contains(className)) {
        return true; // 找到包含指定 class 的父元素
      }
      parent = parent?.parentNode; // 继续向上查找父元素
    }
    return false;
  },
  /**
   获取当前年月日
   */
  getDateString: () => {
    const date = new Date();
    const year = date.getFullYear(); // 年
    const month = (date.getMonth() + 1).toString().padStart(2, "0"); // 月（注意月份是从 0 开始计数的，所以要加 1）
    const day = date.getDate().toString().padStart(2, "0"); // 日
    const hours = date.getHours().toString().padStart(2, "0"); // 时
    const minutes = date.getMinutes().toString().padStart(2, "0"); // 分
    return `${year}年${month}月${day}日 ${hours}:${minutes}`;
  },
  /**
   深拷贝
   */
  deepClone: (obj) => {
    if (obj === null || typeof obj !== "object") {
      return obj;
    }
    var newObj = Array.isArray(obj) ? [] : {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        newObj[key] = utils.deepClone(obj[key]);
      }
    }
    return newObj;
  },

  getHexOpacityColor: ({ color = "#000", opacity = 0.5 }) => {
    opacity = Math.max(opacity, 0);
    opacity = Math.min(opacity, 1);
    color = color.replace(/\#/g, "").toUpperCase();
    if (color.length === 3) {
      let arr = color.split("");
      color = "";
      for (let i = 0; i < arr.length; i++) {
        color += arr[i] + arr[i]; //将简写的3位字符补全到6位字符
      }
    }
    let num = Math.round(255 * opacity); //四舍五入
    let str = "";
    let arrHex = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
    ]; //十六进制数组
    while (num > 0) {
      let mod = num % 16;
      num = (num - mod) / 16;
      str = arrHex[mod] + str;
    }
    if (str.length == 1) str = "0" + str;
    if (str.length == 0) str = "00";
    return `#${color + str}`;
  },

  ...shareds,

  goProcessContract: (queryInfo) => {
    let fullPath = "/contract/approvalProcess";
    let queryString = "";
    if (!_.isEmpty(queryInfo)) {
      queryString = shareds.objectToQueryString(queryInfo);
      fullPath = fullPath + "?" + queryString;
    }
    window.microApp.forceDispatch({
      type: "SetMicroPages",
      microInfo: {
        microId: `org_process_contract${queryString}`,
        app: "org",
        name: "合同审核流程",
        url: fullPath,
      },
    });
  },
};

const getMenuByUserMenu = (menuList, name) => {
  for (let menu of menuList) {
    if (menu.alias == name) {
      return menu;
    }
    if (menu.children && menu.children.length) {
      const result = getMenuByUserMenu(menu.children, name);
      if (result) {
        return result;
      }
    }
  }
};

export default utils;
